import { defineConfig, loadEnv } from "vite";
import type { UserConfig, ConfigEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

import AutoImport from "unplugin-auto-import/vite";   //自动引入ref,reactive等
import Components from "unplugin-vue-components/vite";  //配置按需引入element-plus
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";


// https://vitejs.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  // console.log(command, mode);
  // 获取当前项目所处路径
  const root = process.cwd();
  // 当前所处环境
  const env = loadEnv(mode, root);
  
  return {
    base: "./",
    plugins: [
      vue(),
      AutoImport({
        imports: [
          "vue",
          "vue-router",
          "pinia",
        ],
        dts: "types/auto-import.d.ts", //生成全局引入的文件
        resolvers: [
          ElementPlusResolver() 
        ],
      }),
      Components({
        resolvers: [
          ElementPlusResolver()
        ],
      }),
    ], //配置需要的插件列表
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
            @use "./src/assets/styles/util.scss" as *;
          `,
        },
      },
    },
    // resolver配置
    resolve: {
      // 别名配置
      alias: {
        "@": path.resolve(__dirname, "./src"),
        "@components": path.resolve(__dirname, "./src/components"),
        "@assets": path.resolve(__dirname, "./src/assets"),
        "@images": path.resolve(__dirname, "./src/assets/images"),
        "@views": path.resolve(__dirname, "./src/views"),
        "@store": path.resolve(__dirname, "./src/store"),
        "#": path.resolve(__dirname, "types"),
        "~": path.resolve(__dirname, "./"),
      },
    },
    build: {
      outDir: env.VITE_OUT_DIR || "dist",
      assetsDir: "assets", //指定静态资源存放路径
      sourcemap: false, //是否构建source map文件
      rollupOptions: {
        output: {
          // 最小化拆分包
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id.toString().split("node_modules/")[1].split("/")[0].toString();
            }
          },
          chunkFileNames: "js/[name].[hash].js", //用于命名代码拆分时创建的共享块的输出命名
        },
      },
    },
    assetsInclude: path.resolve(__dirname, "./src/assets"), //静态资源处理
    // 本地运行配置，以及反向代理
    server: {
      cors: true,     //允许跨域
      port: Number(env.VITE_PORT),
      host: "0.0.0.0",
      proxy: {
        //配置代理
      },
    },
  };
});
